package com.example.bidc_work_state;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CheckBox;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.*;


public class MainActivity extends Activity {	
	//URL to get JSON Array
    
    //JSON Node Names 
    private static final String TAG_USERNAME = "Username";
    private static final String TAG_STATUS = "status";    
    public static final String PREFS_NAME = "MyPrefsFile";
    private static final String PREF_USERNAME = "username";
    private static final String PREF_PASSWORD = "password";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText input_username = (EditText) findViewById(R.id.username_textbox);
        final EditText input_password = (EditText) findViewById(R.id.password_textbox);
        final TextView view_username = (TextView) findViewById(R.id.textview_username);
        final TextView view_password = (TextView) findViewById(R.id.textview_password);
        final Button button_loggin = (Button) findViewById(R.id.button1);                
         
        //Press button login event
        OnClickListener loggin = new OnClickListener() {			
			@Override
			public void onClick(View v) {
			    String username = "";
			    String status = "";
			    
/*			    CheckBox chkRememberMe = (CheckBox) findViewById(R.id.checkbox_remember_me);*/
				view_username.setText(input_username.getText().toString());
				view_password.setText(input_password.getText().toString());			
				
			    //ADD THIS  TO  READ  SAVED  username & password  NEXT-TIME OPENING Application
			    SharedPreferences loginPreferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
			    input_username.setText(loginPreferences.getString(PREF_USERNAME, ""));
			    input_password.setText(loginPreferences.getString(PREF_PASSWORD, ""));
		        
		        JsonReader json_reader = new JsonReader();
		        String url = "http://113.161.70.47:8013/api/Login?userName=" + input_username.getText().toString() + "&password=" + input_password.getText().toString();
		        
		        String result = json_reader.readJSONFeed(url);
		        
		        try {
		        	
		            JSONObject jsonObject = new JSONObject(result);            
			            
			            username = jsonObject.getString(TAG_USERNAME);
			            status = jsonObject.getString(TAG_STATUS);
			            
			        	/*//Importing TextView
			            final TextView uid = (TextView)findViewById(R.id.uid);
			            final TextView name1 = (TextView)findViewById(R.id.name);
			            final TextView date = (TextView)findViewById(R.id.due_date);*/
			 
			            //Set JSON Data in TextView
			/*            uid.setText(id);
			            name1.setText(name);
			            date.setText(due_date);*/            
		            
		        } catch (Exception e) {
		            Log.d("error", e.getLocalizedMessage());
		        } 												
				
				if(!input_username.getText().toString().equals(username) || status == "true")
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
					builder.setTitle("Error input");
					builder.setMessage("Please enter a valid user or password");
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub							
						}
					});
					builder.show();
				}
				else
				{			
					Intent mainview_intent = new Intent(getApplicationContext(),MainViewActivity.class);
					startActivity(mainview_intent);
				}				
			}
		};
		button_loggin.setOnClickListener(loggin);
		super.onPause();	
    }    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);        
        return true;
    }
   
  //This method will take URL string then connect to server and get a JSON string return from server
  	public String readJSONFeed(String URL) {
          StringBuilder stringBuilder = new StringBuilder();
          HttpClient httpClient = new DefaultHttpClient();
          HttpGet httpGet = new HttpGet(URL);
          try {
              HttpResponse response = httpClient.execute(httpGet);
              StatusLine statusLine = response.getStatusLine();
              int statusCode = statusLine.getStatusCode();
              if (statusCode == 200) {
                  HttpEntity entity = response.getEntity();
                  InputStream inputStream = entity.getContent();
                  BufferedReader reader = new BufferedReader(
                          new InputStreamReader(inputStream));
                  String line;
                  while ((line = reader.readLine()) != null) {
                      stringBuilder.append(line);
                  }
                  inputStream.close();
              } else {
                  Log.d("JSON", "Failed to download file");
              }
          } catch (Exception e) {
              Log.d("readJSONFeed", e.getLocalizedMessage());
          } 
          return stringBuilder.toString();
      }
      
  	//This method is used to call method "readJSONFeed" asynchronously
      private class ReadWeatherJSONFeedTask extends AsyncTask
      <String, Void, String> {
      	
      	//The doInBackGround() method is executed asynchronously
          protected String doInBackground(String... urls) {
              return readJSONFeed(urls[0]);
          }
          
          //The onPostExecute() method takes the JSON result and parses it..
          protected void onPostExecute(String result) {
              try {
              	
              	//JSON string is passed as the argument to the constructor of the JSONObject class. 
              	//This creates a new JSONObject object (jsonObject) with key/value mappings from the JSON string.
                  JSONObject jsonObject = new JSONObject(result);
   
                  //You then get the value of the weatherObservation key by using the getString() method of jsonObject. 
                  //The values are then passed as the constructor of the JSONObject class, creating another JSONObject - weatherObservationItems.
                  JSONObject weatherObservationItems = 
                          new JSONObject(jsonObject.getString("country_code"));
                  
                  //You extract the value of the clouds and stationName keys by calling the getString() method of weatherObservationItems.
                  Toast.makeText(getBaseContext(), 
                      weatherObservationItems.getString("country_code") + weatherObservationItems.getString("ip") +
                   " - " + weatherObservationItems.getString("country_name"), 
                   Toast.LENGTH_SHORT).show();
              } catch (Exception e) {
                  Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
              }          
          }       
      }    
}
